<template>
  <div>
    <van-nav-bar title="黑马头条 - 登录" />

    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        required
        placeholder="手机号"
        :rules="[{
        required: true,
        message: '请填写正确的手机号',
        trigger:'onChange',
        pattern:/^1[3456789]\d{9}$/
        }]"
      />
      <van-field
        v-model="code"
        type="password"
        name="code"
        label="密码"
        required
        placeholder="密码"
        :rules="[{
        required: true,
        message: '请填写登录密码',
        trigger:'onChange',
        pattern:/^\d{6}$/
        }]"
      />
      <div style="margin: 16px">
        <van-button
        round
        block
        :disabled='isLoading'
        :loading='isLoading'
        loading-text="拼命加载ing..."
        type="info"
        native-type="submit" >
        提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
import { Notify } from 'vant'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      mobile: '13888888888',
      code: '246810',
      isLoading: false
    }
  },
  methods: {
    ...mapMutations(['setToken', 'refreshToken']),
    async onSubmit (values) {
      this.isLoading = true
      console.log('submit', values)
      const [err, res] = await loginAPI(values)
      if (err) {
        Notify({ type: 'warning', message: '账号或密码不正确' })
      } else {
        Notify({ type: 'success', message: '登录成功' })
        // console.log(res)
        const { token, refresh_token } = res.data.data
        this.setToken(token)
        this.refreshToken(refresh_token)
        // 如果登录成功了 跳转到 Layout 首页
        this.$router.push({
          path: '/layout'
        })
      }
      this.isLoading = false
    }
  }
}
</script>

<style>
/* 方案1 - 全局样式表 */
/* scoped会给标签和css选择器都叫上data-v属性选择 */
/* 因为导航组件标签身上有data-v-hash的属性 */
/* .van-nav-bar{
    background:#007bff;
  } */
/* 选择这个类名的时候, 会在后面加[data-v-hash]值来选择这个类名, 但是页面此身上没有data-v-hash属性所以选选择标签不到
  /deep/ 就是把data-v-hash值选择器写到类名的前面 */
/* /deep/.van-nav-bar__title {
    color: white;
  } */
</style>
